/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uy.edu.ort.as.cliente.igu;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import uy.edu.ort.as.cliente.negocio.EntradaBlog;
import uy.edu.ort.as.cliente.negocio.Tag;

/**
 *
 * @author victor
 */
public class JFrameEntradasBlog extends javax.swing.JFrame {
    SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy/MM/dd");

    /**
     * Creates new form JFrameEntradasBlog
     */
    public JFrameEntradasBlog() {
        initComponents();        
        agregarDatos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnEliminar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblEntradasBlog = new javax.swing.JTable();
        btnAgregar = new javax.swing.JButton();
        lblTitulo = new javax.swing.JLabel();
        btnActualizar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnEliminar.setLabel("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnEditar.setLabel("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        tblEntradasBlog.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Título", "Autor", "Fecha", "Contenido", "Tags"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblEntradasBlog);

        btnAgregar.setLabel("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        lblTitulo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTitulo.setText("Entradas de Blog");

        btnActualizar.setText("Actualizar");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnActualizar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEditar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminar))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(172, 172, 172)
                        .addComponent(lblTitulo)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(lblTitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregar)
                    .addComponent(btnEditar)
                    .addComponent(btnEliminar)
                    .addComponent(btnActualizar))
                .addContainerGap())
        );

        lblTitulo.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        JFrameAgregarEntradasBlog jfapw = new JFrameAgregarEntradasBlog(this);
        jfapw.setVisible(true);
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        int indice = tblEntradasBlog.getSelectedRow();
        if (indice == -1) {
            JOptionPane.showMessageDialog(this, "Seleccione un elemento");
        } else {
            try {
                EntradaBlog entrada = getEntradaBlog(indice);

                JFrameEditarEntradaBlog jfepw = new JFrameEditarEntradaBlog(this, indice, entrada);
                jfepw.setVisible(true);
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(this, "El valor ingresado para la fecha no es correcto");
            }
        }
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        try {
            eliminar(tblEntradasBlog);
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, "El valor de la fecha del elemento no es correcto");
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnActualizarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JTable tblEntradasBlog;
    // End of variables declaration//GEN-END:variables

    private void eliminar(JTable tabla) throws ParseException {
        int indice = tabla.getSelectedRow();
        if (indice == -1) {
            JOptionPane.showMessageDialog(this, "Seleccione un elemento");
        } else {
            int res = JOptionPane.showConfirmDialog(this, "¿Esta seguro que quiere eliminar la entrada de blog?", "¡Atención!", JOptionPane.OK_CANCEL_OPTION);
            if (res == JOptionPane.OK_OPTION) {
                EntradaBlog entrada = getEntradaBlog(indice);
                
                //borrar entrada

                ((DefaultTableModel)tblEntradasBlog.getModel()).removeRow(indice);
                int filas = ((DefaultTableModel)tblEntradasBlog.getModel()).getRowCount();

                if (filas > 0) {
                    if (indice < filas) {
                        seleccionarFila(tabla, indice);
                    } else {
                        seleccionarFila(tabla, filas - 1);
                    }
                }
            }
        }
    }

    EntradaBlog getEntradaBlog(int indice) throws ParseException {
        EntradaBlog entrada = new EntradaBlog();
        
        entrada.setTitulo(tblEntradasBlog.getValueAt(indice, 0).toString());
        entrada.setAutor(tblEntradasBlog.getValueAt(indice, 1).toString());
        entrada.setFecha(formatoFecha.parse(tblEntradasBlog.getValueAt(indice, 2).toString()));
        entrada.setContenido(tblEntradasBlog.getValueAt(indice, 3).toString());
        String[] strTags = tblEntradasBlog.getValueAt(indice, 4).toString().split(";");
        ArrayList<Tag> tags = new ArrayList<>();
        for (String s : strTags) {
            Tag tag = new Tag(s);
            tags.add(tag);
        }
        entrada.setTags(tags);
        
        return entrada;
    }

    void seleccionarFila(JTable tabla, int fila) {
        ListSelectionModel selectionModel = tabla.getSelectionModel();
        selectionModel.setSelectionInterval(fila, fila);
    }

    void agregarEntradaBlog(EntradaBlog entrada) {
        DefaultTableModel modelo = (DefaultTableModel)tblEntradasBlog.getModel();
        String strTags = "";
        for(Tag t : entrada.getTags()) {
            strTags += (strTags.equals("") ? "" : ";") + t.getValor();
        }
        Object[] row = new Object[]{entrada.getTitulo(), entrada.getAutor(), formatoFecha.format(entrada.getFecha()), entrada.getContenido(), strTags};
        modelo.addRow(row);
    }

    void editarEntradaBlog(int indice, EntradaBlog entrada) {
        DefaultTableModel modelo = (DefaultTableModel)tblEntradasBlog.getModel();
        modelo.setValueAt(entrada.getTitulo(), indice, 0);
        modelo.setValueAt(entrada.getAutor(), indice, 1);
        modelo.setValueAt(formatoFecha.format(entrada.getFecha()), indice, 2);
        modelo.setValueAt(entrada.getContenido(), indice, 3);
        String strTags = "";
        for(Tag t : entrada.getTags()) {
            strTags += (strTags.equals("") ? "" : ";") + t.getValor();
        }
        modelo.setValueAt(strTags, indice, 4);
    }

    private void agregarDatos() {
        ArrayList<Tag> tags = new ArrayList();
        try {
            tags.add(new Tag("Películas"));
            tags.add(new Tag("2011"));
            tags.add(new Tag("cine"));
            EntradaBlog entrada = new EntradaBlog("Las 10 mejores películas del 2011", "tutifruti", formatoFecha.parse("2011/12/31"), "Estas son las 10 mejores películas del 2011", tags);
            agregarEntradaBlog(entrada);
            tags.clear();
            tags.add(new Tag("Facebook"));
            tags.add(new Tag("acciones"));
            tags.add(new Tag("bolsa"));
            entrada = new EntradaBlog("Suben las acciones de Facebook", "tutifruti", formatoFecha.parse("2012/03/01"), "Continúa el ascenso de las acciones de Facebook en la bolsa", tags);
            agregarEntradaBlog(entrada);
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }
}
